<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:53:26
 * @LastEditors: wjk
 * @LastEditTime: 2021-02-06 11:09:57
 * @description: 手机登录页
 -->
<template>
  <base-page-view class-name="app-login">
    <view class="bind-box">
      <view class="returnBox" :style="{'top': `${returnButtonTop}rpx`}">
        <b-image src="/static/images/icon/icon_arror_left.png" @click="_back" />
      </view>
      <view v-if="step === 1" class="phoneBox">
        <view class="title">{{ wechat_temp_info ? '绑定手机号' : greetings }}</view>
        <view class="phone" :class="{'activity': phoneNumber}">
          <!-- <country-code @selected="interPhone"></country-code> -->
          <div class="codeBox" @click="interPhone">
            {{ countryCode }}<image src="/static/images/icon/icon_arror_down_sc.png" />
          </div>
          <view class="numberBox">
            <input v-if="countryCode==='+86'" v-model="phoneNumber" type="text" maxlength="13" placeholder-class="input-holder" :placeholder="'请输入您的手机号'" />
            <input v-else v-model="phoneNumber" type="number" maxlength="20" placeholder-class="input-holder" :placeholder="'请输入您的手机号'" />
          </view>
          <image v-if="phoneNumber.length > 0" src="/static/images/icon/icon_close_grey.png" class="close-icon" @click="handleClear" />
        </view>
        <view class="decorate">首次登录将自动注册为碧选账号</view>
        <!-- <view class="butto" :class="{'unselected': messageCode.length !== 6}" @click="loginto">登录</view> -->
        <view v-if="countryCode == '+86'" class="butto" :class="{'unselected': phoneNumber.length !== 13}" @click="verify">获取验证码</view>
        <view v-else class="butto" :class="{'unselected': phoneNumber.length < 1}" @click="verify">获取验证码</view>
      </view>
      <view v-if="step === 2" class="phoneBox">
        <view class="title">{{ '输入验证码' }}
          <view class="decorate">我们向您 <text> {{ phoneNumber.replace(/\s*/g, '') }} </text> 手机号发送了验证码 </view>
        </view>
        <view class="messageCodeShow" @click="setMessageCodeFocus">
          <view class="input-fixed">
            <view class="input-hide">
              <input ref="messageCode" v-model="messageCode" type="number" maxlength="6" placeholder-class="input-holder" @input="loginto" />
            </view>
            <!-- <view class="verifyBox" @click="verify">{{ getVerify }}</view> -->
          </view>
          <view class="code-box height-fix">
            <view v-for="(item, key) in messageCode" :key="key" class="code-item">
              {{ item }}
            </view>
          </view>
          <view class="code-box">
            <view v-for="(k, index) in 6" :key="index" class="code-box-line" :class="{'activity': index === messageCode.length}"></view>
          </view>
        </view>
        <!-- style="height:0; opacity:0;position:fixed;left:-200rpx; top:-200rpx" -->
        <view v-if="getVerify === '重新获取验证码'" class="decorate blue" @click="verify">重新获取验证码</view>
        <view v-else class="decorate"> {{ `${getVerify} 后重新获取` }}   </view>
        <!-- <view class="butto" :class="{'unselected': messageCode.length !== 6}" @click="loginto">登录</view> -->
      </view>
    </view>
  </base-page-view>
</template>

<script>
import { bindInviteCode } from '@/utils/navigateTo'
import { getGreeting } from '@/utils/common'
import { mapState,mapActions } from 'vuex'
import { requestOpenId,getMiniOpenId } from '@/utils/tools.js'
import './index.scss'
export default {
  data() {
    return {
      isShow: false,
      phoneNumber: '',
      verifyCode: '',
      step: 1,
      countryCode: '+86',
      getVerify: '重新获取验证码',
      messageCode: '',
      invideCode: '',
      wechat_temp_info: null,
      returnButtonTop: 35
    }
  },
  computed: {
    greetings() {
      return getGreeting()
    },
    ...mapState([
      'token',
      'userInfo'
    ])
  },
  watch: {
    phoneNumber(newValue, oldValue) {
      if (this.countryCode !== '+86') {
        return
      }
      this.phoneNumber = newValue.length > oldValue.length ? newValue.replace(/\s/g, '').replace(/(\d{3})(\d{0,4})(\d{0,4})/, '$1 $2 $3') : this.phoneNumber.trim()
    }
  },
  created() {
  },
  onLoad(option) {
    // #ifdef MP-WEIXIN
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    this.returnButtonTop = menuButtonInfo.top * 2 + 14
    // #endif
    if (option.type === 'bind') {
      uni.getStorage({
        key: 'wechat_temp_info',
        success: async({ data }) => {
          this.wechat_temp_info = data
        }
      })
    }
  },
  onShow() {
    console.log('option', uni.getStorageSync('countryCode'))
    if (uni.getStorageSync('countryCode')) {
      this.countryCode = uni.getStorageSync('countryCode')
    }
  },
  methods: {
    ...mapActions([
      'GetUserInfo'
    ]),
    _back() {
      uni.redirectTo({
        url: '/pages/login/index'
      })
    },
    verify() {
      switch (this.countryCode) {
        case '+86':
          if (this.getVerify !== '重新获取验证码' || this.phoneNumber.length !== 13) {
            return
          }
          if (!(/^\d{11}$/.test(this.phoneNumber.replace(/\s*/g, ''))) && this.countryCode === '+86') {
            uni.showToast({
              title: '请输入正确的手机号',
              icon: 'none',
              duration: 2 * 1000
            })
          } else {
            this.subcli()
          }
          break
        default:
          this.subcli()
      }
    },
    async subcli() {
      const res = await this.$api.loginApi.sendSms(this.countryCode, this.phoneNumber.replace(/\s*/g, ''))
      if (res.code) {
        return
      }
      this.step = 2
      uni.showToast({
        title: '短信发送成功，请注意查收！',
        icon: 'none',
        duration: 2 * 1000
      })
      this.value = 60
      this.getVerify = this.value + 's'
      var timers = setInterval(() => {
        this.value--
        this.getVerify = this.value + 's'
        if (this.value <= 0) {
          clearInterval(timers)
          this.getVerify = '重新获取验证码'
        }
      }, 1000)
    },
    setMessageCodeFocus() {
      // #ifdef H5
      // this.$nextTick(() => {
      //   this.$refs.messageCode.focus()
      // })
      // #endif
    },
    // 选择国家
    interPhone() {
      this.$navigateTo('/customComponent/phoneList')
    },
    goRule(type) {
      this.$navigateTo('/pagesMine/rule/index?type=' + type)
    },
    async loginto(e) {
      // if (!(/^\d{11}$/.test(this.phoneNumber.replace(/\s*/g, ''))) && this.countryCode === '+86') {
      //   uni.showToast({
      //     title: '请输入正确的手机号',
      //     icon: 'none',
      //     duration: 2 * 1000
      //   })
      //   return
      // }

      if (e.detail.value.length !== 6) {
        // uni.showToast({
        //   title: '短信验证码错误',
        //   icon: 'none',
        //   duration: 2 * 1000
        // })
        return
      }
      let login = {
        region_code: this.countryCode,
        mobile: this.phoneNumber.replace(/\s*/g, ''),
        sms_code: e.detail.value || this.messageCode
      }
      if (this.wechat_temp_info) {
        login = { ...login, ...this.wechat_temp_info }
        const resp = await this.$api.loginApi.wechatBind(login)
        if (!resp.success) {
          return
        }
        this.$store.dispatch('SET_USER', {
          token: resp.data.token,
          userInfo: resp.data.user
        })
        uni.removeStorage({
          key: 'wechat_temp_info'
        })
        this.bindInvite(resp.data)
      } else {
        const response = await this.$api.loginApi.mobileLogin(login)
        if (response.code) {
          return
        }
        this.$store.dispatch('SET_USER', {
          token: response.data.token,
          userInfo: response.data.user
        })
        console.log('userinfo:', response.data.user)
        this.bindInvite(response.data)
      }
      await this.GetUserInfo();//获取用户信息
    },
    async bindInvite(data) {
      await bindInviteCode(this, data)
      setTimeout(() => {
        requestOpenId();//获取公众号openId
        getMiniOpenId();//获取小程序openId
      }, 500)
    },
    getState(code) {
      this.countryCode = code
    },
    handleClear() {
      setTimeout(() => {
        this.phoneNumber = ''
      }, 100)
    }
  }
}
</script>
